import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import type { RouteRecordRaw } from 'vue-router'

// 基础路由
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/DefaultLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'dashboard' }
      },
      // 商品管理
      {
        path: '/products',
        name: 'Products',
        redirect: '/products/list',
        meta: { title: '商品管理', icon: 'goods' },
        children: [
          {
            path: 'list',
            name: 'ProductList',
            component: () => import('@/views/products/list.vue'),
            meta: { title: '商品列表' }
          },
          {
            path: 'add',
            name: 'ProductAdd',
            component: () => import('@/views/products/add.vue'),
            meta: { title: '新增商品' }
          },
          {
            path: 'edit/:id',
            name: 'ProductEdit',
            component: () => import('@/views/products/edit.vue'),
            meta: { title: '编辑商品' }
          },
          {
            path: 'categories',
            name: 'ProductCategories',
            component: () => import('@/views/products/categories.vue'),
            meta: { title: '商品分类' }
          },
          {
            path: 'specs',
            name: 'ProductSpecs',
            component: () => import('@/views/products/specs.vue'),
            meta: { title: '商品规格' }
          }
        ]
      },
      // 订单管理
      {
        path: '/orders',
        name: 'Orders',
        redirect: '/orders/list',
        meta: { title: '订单管理', icon: 'document' },
        children: [
          {
            path: 'list',
            name: 'OrderList',
            component: () => import('@/views/orders/list.vue'),
            meta: { title: '订单列表' }
          },
          {
            path: 'detail/:id',
            name: 'OrderDetail',
            component: () => import('@/views/orders/detail.vue'),
            meta: { title: '订单详情' }
          },
          {
            path: 'refund',
            name: 'OrderRefund',
            component: () => import('@/views/orders/refund.vue'),
            meta: { title: '退款管理' }
          }
        ]
      },
      // 库存管理
      {
        path: '/inventory',
        name: 'Inventory',
        redirect: '/inventory/list',
        meta: { title: '库存管理', icon: 'box' },
        children: [
          {
            path: 'list',
            name: 'InventoryList',
            component: () => import('@/views/inventory/list.vue'),
            meta: { title: '库存列表' }
          },
          {
            path: 'purchase',
            name: 'Purchase',
            component: () => import('@/views/inventory/purchase.vue'),
            meta: { title: '采购管理' }
          },
          {
            path: 'stock-in',
            name: 'StockIn',
            component: () => import('@/views/inventory/stock-in.vue'),
            meta: { title: '入库管理' }
          },
          {
            path: 'stock-out',
            name: 'StockOut',
            component: () => import('@/views/inventory/stock-out.vue'),
            meta: { title: '出库管理' }
          },
          {
            path: 'transfer',
            name: 'StockTransfer',
            component: () => import('@/views/inventory/transfer.vue'),
            meta: { title: '库存调拨' }
          }
        ]
      },
      // 会员管理
      {
        path: '/members',
        name: 'Members',
        redirect: '/members/list',
        meta: { title: '会员管理', icon: 'user' },
        children: [
          {
            path: 'list',
            name: 'MemberList',
            component: () => import('@/views/members/list.vue'),
            meta: { title: '会员列表' }
          },
          {
            path: 'levels',
            name: 'MemberLevels',
            component: () => import('@/views/members/levels.vue'),
            meta: { title: '会员等级' }
          },
          {
            path: 'points',
            name: 'MemberPoints',
            component: () => import('@/views/members/points.vue'),
            meta: { title: '积分管理' }
          }
        ]
      },
      // 营销管理
      {
        path: '/marketing',
        name: 'Marketing',
        redirect: '/marketing/coupons',
        meta: { title: '营销管理', icon: 'promotion' },
        children: [
          {
            path: 'coupons',
            name: 'Coupons',
            component: () => import('@/views/marketing/coupons.vue'),
            meta: { title: '优惠券' }
          },
          {
            path: 'promotions',
            name: 'Promotions',
            component: () => import('@/views/marketing/promotions.vue'),
            meta: { title: '促销活动' }
          },
          {
            path: 'flash-sales',
            name: 'FlashSales',
            component: () => import('@/views/marketing/flash-sales.vue'),
            meta: { title: '限时抢购' }
          },
          {
            path: 'group-buying',
            name: 'GroupBuying',
            component: () => import('@/views/marketing/group-buying.vue'),
            meta: { title: '团购活动' }
          }
        ]
      },
      // 分销管理
      {
        path: '/distribution',
        name: 'Distribution',
        redirect: '/distribution/agents',
        meta: { title: '分销管理', icon: 'share' },
        children: [
          {
            path: 'agents',
            name: 'Agents',
            component: () => import('@/views/distribution/agents.vue'),
            meta: { title: '分销商' }
          },
          {
            path: 'products',
            name: 'DistributionProducts',
            component: () => import('@/views/distribution/products.vue'),
            meta: { title: '分销商品' }
          },
          {
            path: 'orders',
            name: 'DistributionOrders',
            component: () => import('@/views/distribution/orders.vue'),
            meta: { title: '分销订单' }
          },
          {
            path: 'commissions',
            name: 'Commissions',
            component: () => import('@/views/distribution/commissions.vue'),
            meta: { title: '佣金管理' }
          }
        ]
      },
      // 店铺管理
      {
        path: '/shop',
        name: 'Shop',
        redirect: '/shop/info',
        meta: { title: '店铺管理', icon: 'shop' },
        children: [
          {
            path: 'info',
            name: 'ShopInfo',
            component: () => import('@/views/shop/info.vue'),
            meta: { title: '店铺信息' }
          },
          {
            path: 'decoration',
            name: 'ShopDecoration',
            component: () => import('@/views/shop/decoration.vue'),
            meta: { title: '店铺装修' }
          },
          {
            path: 'settings',
            name: 'ShopSettings',
            component: () => import('@/views/shop/settings.vue'),
            meta: { title: '店铺设置' }
          }
        ]
      },
      // 网点管理
      {
        path: '/stores',
        name: 'Stores',
        redirect: '/stores/list',
        meta: { title: '网点管理', icon: 'location' },
        children: [
          {
            path: 'list',
            name: 'StoreList',
            component: () => import('@/views/stores/list.vue'),
            meta: { title: '网点列表' }
          },
          {
            path: 'add',
            name: 'StoreAdd',
            component: () => import('@/views/stores/add.vue'),
            meta: { title: '新增网点' }
          },
          {
            path: 'edit/:id',
            name: 'StoreEdit',
            component: () => import('@/views/stores/edit.vue'),
            meta: { title: '编辑网点' }
          }
        ]
      },
      // 数据统计
      {
        path: '/statistics',
        name: 'Statistics',
        redirect: '/statistics/sales',
        meta: { title: '数据统计', icon: 'data-analysis' },
        children: [
          {
            path: 'sales',
            name: 'SalesStatistics',
            component: () => import('@/views/statistics/sales.vue'),
            meta: { title: '销售统计' }
          },
          {
            path: 'products',
            name: 'ProductStatistics',
            component: () => import('@/views/statistics/products.vue'),
            meta: { title: '商品统计' }
          },
          {
            path: 'members',
            name: 'MemberStatistics',
            component: () => import('@/views/statistics/members.vue'),
            meta: { title: '会员统计' }
          },
          {
            path: 'finance',
            name: 'FinanceStatistics',
            component: () => import('@/views/statistics/finance.vue'),
            meta: { title: '财务统计' }
          }
        ]
      },
      // 数据分析
      {
        path: '/analytics',
        name: 'Analytics',
        redirect: '/analytics/user-behavior',
        meta: { title: '数据分析', icon: 'trend-charts' },
        children: [
          {
            path: 'user-behavior',
            name: 'UserBehavior',
            component: () => import('@/views/analytics/user-behavior.vue'),
            meta: { title: '用户行为' }
          },
          {
            path: 'product-analysis',
            name: 'ProductAnalysis',
            component: () => import('@/views/analytics/product-analysis.vue'),
            meta: { title: '商品分析' }
          },
          {
            path: 'marketing-analysis',
            name: 'MarketingAnalysis',
            component: () => import('@/views/analytics/marketing-analysis.vue'),
            meta: { title: '营销分析' }
          }
        ]
      },
      // 系统管理
      {
        path: '/system',
        name: 'System',
        redirect: '/system/users',
        meta: { title: '系统管理', icon: 'setting' },
        children: [
          {
            path: 'users',
            name: 'SystemUsers',
            component: () => import('@/views/system/users.vue'),
            meta: { title: '用户管理' }
          },
          {
            path: 'roles',
            name: 'SystemRoles',
            component: () => import('@/views/system/roles.vue'),
            meta: { title: '角色管理' }
          },
          {
            path: 'permissions',
            name: 'SystemPermissions',
            component: () => import('@/views/system/permissions.vue'),
            meta: { title: '权限管理' }
          },
          {
            path: 'logs',
            name: 'SystemLogs',
            component: () => import('@/views/system/logs.vue'),
            meta: { title: '操作日志' }
          },
          {
            path: 'monitor',
            name: 'SystemMonitor',
            component: () => import('@/views/system/monitor.vue'),
            meta: { title: '系统监控' }
          }
        ]
      },
      // 应用配置
      {
        path: '/config',
        name: 'Config',
        redirect: '/config/system',
        meta: { title: '应用配置', icon: 'tools' },
        children: [
          {
            path: 'system',
            name: 'SystemConfig',
            component: () => import('@/views/config/system.vue'),
            meta: { title: '系统配置' }
          },
          {
            path: 'payment',
            name: 'PaymentConfig',
            component: () => import('@/views/config/payment.vue'),
            meta: { title: '支付配置' }
          },
          {
            path: 'shipping',
            name: 'ShippingConfig',
            component: () => import('@/views/config/shipping.vue'),
            meta: { title: '物流配置' }
          },
          {
            path: 'message',
            name: 'MessageConfig',
            component: () => import('@/views/config/message.vue'),
            meta: { title: '消息配置' }
          }
        ]
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 电商后台` : '电商后台'
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    if (!authStore.isAuthenticated) {
      next('/login')
      return
    }
    
    // 检查权限
    if (to.meta.permission && !authStore.hasPermission(to.meta.permission)) {
      next('/403')
      return
    }
  }
  
  next()
})

export default router
